# ~*~ coding: utf-8 ~*~
import time
from datetime import timedelta

from apps.common.dbbase import BaseModel
from apps.common.utils import generate_uuid
from apps.extensions import db

from celery import schedules

__all__ = ['IntervalSchedule']


class IntervalSchedule(BaseModel):
    __tablename__ = 'tasks_periodic_schedule_interval'

    DAYS = 'days'
    HOURS = 'hours'
    MINUTES = 'minutes'
    SECONDS = 'seconds'
    MICROSECONDS = 'microseconds'

    id = db.Column(db.String(36), default=generate_uuid, primary_key=True)
    period = db.Column(db.String(24), nullable=False)
    every = db.Column(db.Integer(), nullable=False)

    create_by = db.Column(db.VARCHAR(32), nullable=True)
    create_time = db.Column(db.INT, default=time.time)
    update_time = db.Column(db.INT, default=time.time, onupdate=time.time)

    @property
    def schedule(self):
        return schedules.schedule(
            run_every=timedelta(**{self.period: self.every})
        )

    def __str__(self):
        return ' '.join([str(self.every), self.period])
